/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.Workspace;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import managedbean.LoginAdmin.LoginManagerBean;
import merlion.common.entity.JobToDo;
import merlion.common.entity.Staff;
import merlion.common.session.stateless.JobListSessionBeanLocal;
import merlion.common.util.Consts;
import merlion.crm.sopm.entity.SalesOrder;
import merlion.crm.sopm.entity.SalesQuotation;
import merlion.scm.lcm.entity.DeliveryOrder;

/**
 *
 * @author Zhang Ying
 */
@ManagedBean(name = "jobManagerBean")
@ViewScoped
public class JobManagerBean {

    @EJB
    private JobListSessionBeanLocal jobListManager;
    @ManagedProperty(value = "#{workspaceManagerBean}")
    private WorkspaceManagerBean workspaceManagerBean;
    // for view my job lists
    private String[] jobStatus;
    private Collection<JobToDo> myJobs;
    private JobToDo selectedJob;
    // for view job list of one type
    private Collection<JobToDo> oneDepJobs;

    /** Creates a new instance of JobManagerBean */
    public JobManagerBean() {
    }

    // for system adding new job
    public String addJobATPSO(Long salesOrderId) {
        this.addNewJob(Consts.JOB_TYPE_ATP_SO, salesOrderId);
        return null;
    }

    public String addJobATPSQ(Long salesQuotationId) {
        this.addNewJob(Consts.JOB_TYPE_ATP_SQ, salesQuotationId);
        return null;
    }

    public String addJobCC(Long salesOrderId) {
        this.addNewJob(Consts.JOB_TYPE_CC, salesOrderId);
        return null;
    }

    public String addJobInvoiceCIA(Long salesOrderId) {
        this.addNewJob(Consts.JOB_TYPE_INVOICE_CIA, salesOrderId);
        return null;
    }

    public String assignJobInvoiceCIA(Long salesOrderId) {
        this.assignNewJob(Consts.JOB_TYPE_INVOICE_CIA, salesOrderId);
        return null;
    }

    public String assignJobInvoiceCC(Long doId) {
        this.assignNewJob(Consts.JOB_TYPE_INVOICE_CC, doId);
        return null;
    }
    
    public String assignJobRefundCIA(Long doId) {
        this.assignNewJob(Consts.JOB_TYPE_REFUND_CIA, doId);
        return null;
    }

    public void assignNewJob(String jobType, Long relatedObjectId) {
        if (jobListManager.haveThisJobAlready(jobType, relatedObjectId)) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Previously Initiated this job already", "Previously Initiated this job already"));
            return;
        }
        JobToDo jobTD = new JobToDo();
        jobTD.setJobType(jobType);
        jobTD.setRelatedId(relatedObjectId);
        jobTD.setStatus(Consts.JOB_STATUS_PENDING);
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        Timestamp currentTime = new Timestamp(date.getTime());
        jobTD.setCreatedDate(currentTime);
        // add more jobs here
        if (jobType.equals(Consts.JOB_TYPE_INVOICE_CIA)) {
            DeliveryOrder dor1 = jobListManager.getRelatedDeliveryOrder(relatedObjectId);
            SalesOrder so1 = dor1.getSalesOrder();
            jobTD.setTitle(Consts.JOB_TYPE_INVOICE_CIA_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_INVOICE_CIA_CONTENT + so1.getSalesOrderIdStr()+ " with Delivery Order ID " + dor1.getDeliveryOrderIdStr());
            jobListManager.addNewJob(so1.getCustomer().getFinanceStaff().getSystemUserAccount().getId(), jobTD);
        } else if (jobType.equals(Consts.JOB_TYPE_INVOICE_CC)) {
            DeliveryOrder dor = jobListManager.getRelatedDeliveryOrder(relatedObjectId);
            SalesOrder so = dor.getSalesOrder();
            jobTD.setTitle(Consts.JOB_TYPE_INVOICE_CC_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_INVOICE_CC_CONTENT + so.getSalesOrderIdStr() + " with Delivery Order ID " + dor.getDeliveryOrderIdStr());
            jobListManager.addNewJob(so.getCustomer().getFinanceStaff().getSystemUserAccount().getId(), jobTD);
        } else if (jobType.equals(Consts.JOB_TYPE_ATP_SO)) {
            // ATP check for sales order
            SalesOrder so = jobListManager.getRelatedSalesOrder(relatedObjectId);
            jobTD.setTitle(Consts.JOB_TYPE_ATP_SO_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_ATP_SO_CONTENT + "  " + so.getSalesOrderIdStr());
            jobListManager.addNewJob(so.getCustomer().getCustomerExecutive().getSystemUserAccount().getId(), jobTD);
        } else if (jobType.equals(Consts.JOB_TYPE_ATP_SQ)) {
            // ATP check for sales quotation
            SalesQuotation sq = jobListManager.getRelatedSalesQuotation(relatedObjectId);
            jobTD.setTitle(Consts.JOB_TYPE_ATP_SQ_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_ATP_SQ_CONTENT + " " + sq.getSqNumber());
            jobListManager.addNewJob(sq.getClient().getCustomerExecutive().getSystemUserAccount().getId(), jobTD);
        } else if (jobType.equals(Consts.JOB_TYPE_ATP_SQ_URGENT)) {
            // ATP check for sales quotation
            DeliveryOrder deo = jobListManager.getRelatedDeliveryOrder(relatedObjectId);
            jobTD.setTitle(Consts.JOB_TYPE_ATP_SQ_URGENT_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_ATP_SQ_URGENT_CONTENT + " " + deo.getSalesQuotation().getSqNumber());
            jobListManager.addNewJob(deo.getSalesQuotation().getClient().getCustomerExecutive().getSystemUserAccount().getId(), jobTD);
        } else if (jobType.equals(Consts.JOB_TYPE_ATP_DO_FAIL)) {
            DeliveryOrder deo = jobListManager.getRelatedDeliveryOrder(relatedObjectId);
            jobTD.setTitle(Consts.JOB_TYPE_ATP_DO_FAIL_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_ATP_DO_FAIL_CONTENT + " " + deo.getSalesOrder().getSalesOrderIdStr());
            jobListManager.addNewJob(deo.getSalesOrder().getCustomer().getCustomerExecutive().getSystemUserAccount().getId(), jobTD);
        } else if (jobType.equals(Consts.JOB_TYPE_ATP_RFQ_FAIL)) {
            SalesQuotation sq = jobListManager.getRelatedSalesQuotation(relatedObjectId);
            jobTD.setTitle(Consts.JOB_TYPE_ATP_RFQ_FAIL_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_ATP_RFQ_FAIL_CONTENT + " " + sq.getSqNumber());
            jobListManager.addNewJob(sq.getClient().getCustomerExecutive().getSystemUserAccount().getId(), jobTD);
        } else if(jobType.equals(Consts.JOB_TYPE_REFUND_CIA)) {
            DeliveryOrder dor2 = jobListManager.getRelatedDeliveryOrder(relatedObjectId);
            SalesOrder so2 = dor2.getSalesOrder();
            jobTD.setTitle(Consts.JOB_TYPE_REFUND_CIA_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_REFUND_CIA_CONTENT + so2.getSalesOrderIdStr()+ " with Customer Payment Record ID " + dor2.getInvoice().getCustomerPaymentRecord().getCustomerPaymentRecordId());
            jobListManager.addNewJob(so2.getCustomer().getFinanceStaff().getSystemUserAccount().getId(), jobTD);
        }
        updateCurrentStaff();
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "Add Job Successfully.", "Add Job Successfully."));

    }

    public void addNewJob(String jobType, Long relatedObjectId) {
        if (jobListManager.haveThisJobAlready(jobType, relatedObjectId)) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Previously Initiated this job already", "Previously Initiated this job already"));
            return;
        }
        JobToDo jobTD = new JobToDo();
        jobTD.setJobType(jobType);
        jobTD.setRelatedId(relatedObjectId);
        jobTD.setStatus(Consts.JOB_STATUS_PENDING);
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        Timestamp currentTime = new Timestamp(date.getTime());
        jobTD.setCreatedDate(currentTime);
        // add more jobs here
        if (jobType.equals(Consts.JOB_TYPE_ATP_SO)) {
            // ATP check for sales order
            SalesOrder so = jobListManager.getRelatedSalesOrder(relatedObjectId);
            jobTD.setTitle(Consts.JOB_TYPE_ATP_SO_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_ATP_SO_CONTENT + "  " + so.getSalesOrderIdStr());
        } else if (jobType.equals(Consts.JOB_TYPE_CC)) {
            // CC for sales order
            SalesOrder so = jobListManager.getRelatedSalesOrder(relatedObjectId);
            jobTD.setTitle(Consts.JOB_TYPE_CC_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_CC_CONTENT + " " + so.getSalesOrderIdStr());
        } else if (jobType.equals(Consts.JOB_TYPE_ATP_SQ)) {
            // ATP check for sales quotation
            SalesQuotation sq = jobListManager.getRelatedSalesQuotation(relatedObjectId);
            jobTD.setTitle(Consts.JOB_TYPE_ATP_SQ_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_ATP_SQ_CONTENT + " " + sq.getRfqNumber());
        } else if (jobType.equals(Consts.JOB_TYPE_INVOICE_CIA)) {
            SalesOrder so = jobListManager.getRelatedSalesOrder(relatedObjectId);
            jobTD.setTitle(Consts.JOB_TYPE_INVOICE_CIA_TITLE);
            jobTD.setContent(Consts.JOB_TYPE_INVOICE_CIA_CONTENT + " " + so.getSalesOrderIdStr());
        }
        jobListManager.addNewJob(workspaceManagerBean.getCurrentStaff().getSystemUserAccount().getId(), jobTD);
        updateCurrentStaff();
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "Add Job Successfully.", "Add Job Successfully."));
    }

    // for view my job lists
    public String viewMyJobListOne(Long id) {
        return redirectToViewJobOne() + "&jobId=" + id;
    }

    public String markSelectedAsDone() {
        if (jobListManager.markJobStatusAsDone(selectedJob.getId())) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Marked Successful.", "Marked Successful."));
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Marked Failed", "Marked Failed"));
        }
        selectedJob = jobListManager.getJobToDo(selectedJob.getId());
        return null;
    }

    public JobToDo getSelectedJob() {
        if (selectedJob == null) {
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            String parameter = request.getParameter("jobId");
            if (parameter != null) {
                Long id = Long.valueOf(parameter);
                selectedJob = jobListManager.getJobToDo(id);
            }
        }
        return selectedJob;
    }

    public void setSelectedJob(JobToDo selectedJob) {
        this.selectedJob = selectedJob;
    }

    public Collection<JobToDo> getMyJobs() {
        myJobs = jobListManager.getAllMyJobs(workspaceManagerBean.getCurrentStaff().getSystemUserAccount().getId());
        return myJobs;
    }

    public void setMyJobs(Collection<JobToDo> myJobs) {
        this.myJobs = myJobs;
    }

    public String[] getJobStatus() {
        if (jobStatus == null) {
            jobStatus = new String[2];
            jobStatus[0] = Consts.JOB_STATUS_FINISHED;
            jobStatus[1] = Consts.JOB_STATUS_PENDING;
        }
        return jobStatus;
    }

    public void setJobStatus(String[] jobStatus) {
        this.jobStatus = jobStatus;
    }

    // for view job list of one dep
    public Collection<JobToDo> getOneDepJobs() {
        oneDepJobs = jobListManager.getJobsFromDep(workspaceManagerBean.getCurrentStaff().getDepartment());
        return oneDepJobs;
    }

    public String getStaffFullNameByJobId(Long id) {
        return jobListManager.getStaffByJobId(id).getFullName();
    }

    public String viewJobOneDepOne(Long id) {
        return redirectToViewOneDepOne() + "&jobId=" + id;
    }

    public void setOneDepJobs(Collection<JobToDo> oneDepJobs) {
        this.oneDepJobs = oneDepJobs;
    }

    // for general purpose
    public WorkspaceManagerBean getWorkspaceManagerBean() {
        return workspaceManagerBean;
    }

    public void setWorkspaceManagerBean(WorkspaceManagerBean workspaceManagerBean) {
        this.workspaceManagerBean = workspaceManagerBean;
    }

    private void updateCurrentStaff() {
        Staff s = jobListManager.getUpdatedStaff(workspaceManagerBean.getCurrentStaff().getId());
        workspaceManagerBean.setCurrentStaff(s);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(LoginManagerBean.AUTH_KEY, s);
    }

    private String getRedirectPath(String path) {
        return path + "?faces-redirect=true";
    }

    public String redirectToViewJobOne() {
        return getRedirectPath(Consts.VIEW_MY_JOB_LIST_ONE);
    }

    public String redirectToViewMyJobs() {
        return getRedirectPath(Consts.VIEW_MY_JOB_LIST);
    }

    public String redirectToViewOneDep() {
        return getRedirectPath(Consts.VIEW_JOB_LIST_ONE_DEP_PATH);
    }

    public String redirectToViewOneDepOne() {
        return getRedirectPath(Consts.VIEW_JOB_LIST_ONE_DEP_PATH + "One");
    }

    // for home page
    public Collection<JobToDo> getAllMyPendingJobsDESC(Long accId) {
        return jobListManager.getAllMyPendingJobsDESC(accId);
    }
}
